﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace Neuron.Cell
{

    public delegate void DelegateTriggerEvent();

    class Trigger
    {

        public event DelegateTriggerEvent TriggerEvent;

        private Thread _thread = null;
        private int _milliseconds = 0;
        private bool _running = false;

        private DateTime _lastTrigger = DateTime.MinValue;

        public Trigger(int milliseconds)
        {
            this._milliseconds = milliseconds;
        }

        public void Start()
        {
            this._running = true;
            this._thread = new Thread(this.ThreadMethod);
            this._thread.Start();
            while (!this._thread.IsAlive) ;

            _lastTrigger = DateTime.MinValue;
        }

        public void Stop()
        {
            this._running = false;
            if (this._thread != null)
            {
                while (!this._thread.IsAlive) ;
                this._thread.Abort();
                this._thread = null;
            }
        }

        private void ThreadMethod()
        {
            while (this._running)
            {
                TimeSpan ts = DateTime.Now - this._lastTrigger;
                if (ts.TotalMilliseconds >= this._milliseconds)
                {
                    if (this.TriggerEvent != null)
                    {
                        this.TriggerEvent();
                    }
                    this._lastTrigger = DateTime.Now;
                }
            }
        }
    }
}
